/*
 * The MIT License
 *
 * Copyright 2013 jdmr.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.ly.wxstore.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.imgscalr.Scalr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ly.wxstore.entity.Image;
import com.ly.wxstore.service.ImageService;
import com.ly.wxstore.service.account.ShiroDbRealm.ShiroUser;
import com.ly.wxstore.utils.ServerPathUtils;

/**
 * 
 * @author jdmr
 */
@Controller
@RequestMapping(value = "/my/image")
public class ImageController {

	private static Logger logger = LoggerFactory.getLogger(ImageController.class);

	@Autowired
	private ImageService imageService;


	// 上传图片
	@RequestMapping(value = "/upload")
	@ResponseBody
	public Map<String, Object> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
		logger.debug("uploadPost called");
		Iterator<String> itr = request.getFileNames();

		//String systemId = request.getParameter("systemId");
		String phase = request.getParameter("phase");

		MultipartFile mpf;
		List<Image> list = new LinkedList<Image>();

		while (itr.hasNext()) {
			mpf = request.getFile(itr.next());
			logger.debug("Uploading {}", mpf.getOriginalFilename());

			String newFilenameBase = UUID.randomUUID().toString();
			String originalFileExtension = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
			String newFilename = newFilenameBase + originalFileExtension;
			// String storageDirectory = fileUploadDirectory;
			String storageDirectory = ServerPathUtils.getImageDir(request);// 绝对路径

			String contentType = mpf.getContentType();

			File newFile = new File(storageDirectory + File.separator + newFilename);
			try {
				
				
				mpf.transferTo(newFile);
				
				//大图
				BufferedImage thumbnailBig = Scalr.resize(ImageIO.read(newFile), Scalr.Method.SPEED, Scalr.Mode.FIT_TO_WIDTH, 600, 600, Scalr.OP_ANTIALIAS);// 生产缩略图
				String thumbnailFilenameBig = newFilenameBase + "-big.png";
				File thumbnailFileBig = new File(storageDirectory + File.separator + thumbnailFilenameBig);
				ImageIO.write(thumbnailBig, "png", thumbnailFileBig);

				//小图
				BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), Scalr.Method.SPEED, Scalr.Mode.FIT_TO_WIDTH, 100, 100, Scalr.OP_ANTIALIAS);// 生产缩略图
				String thumbnailFilename = newFilenameBase + "-thumbnail.png";
				File thumbnailFile = new File(storageDirectory + File.separator + thumbnailFilename);
				ImageIO.write(thumbnail, "png", thumbnailFile);

				Image image = new Image();
				image.setName(mpf.getOriginalFilename());
				image.setSize(mpf.getSize());
				image.setThumbnailFilename(thumbnailFilename);
				image.setThumbnailSize(thumbnailFile.length());
				
				image.setNewFilename(thumbnailFilenameBig);//大图
				image.setContentType(contentType);
				image.setCreateDate(new Date());
				image.setUpdateDate(new Date());
				image.setCreateUser(1L);
				image.setPhase(phase);
				image.setUuid(newFilenameBase);
				image.setUid(getCurrentUser().getUid());

				imageService.save(image);

				image.setUrl(image.getNewFilename());
				image.setThumbnailUrl(image.getThumbnailFilename());
				image.setDeleteUrl("/my/image/delete/" + image.getUuid());
				image.setDeleteType("DELETE");
				

				list.add(image);
				logger.info("Uploading {}", image);

			} catch (IOException e) {
				logger.error("Could not upload file " + mpf.getOriginalFilename(), e);
			}

		}

		Map<String, Object> files = new HashMap<String, Object>();
		files.put("files", list);
		return files;
	}


	// 加载已存在的图片
	@RequestMapping(value = "/load/{uid}", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> list( @PathVariable("uid") String uid, Model model) {
		logger.debug("uploadGet called");
		Image search = new Image();
		search.setUuid(uid);

		List<Image> list = imageService.search(search);
		// List<Image> list = new ArrayList<Image>();
		for (Image image : list) {
			image.setUrl( image.getNewFilename());
			image.setThumbnailUrl(image.getThumbnailFilename());
			image.setDeleteUrl("/my/image/delete/" + image.getUuid());
			image.setDeleteType("DELETE");
		}
		Map<String, Object> files = new HashMap<String, Object>();
		files.put("files", list);
		logger.debug("Returning: {}", files);
		return files;
	}

	@RequestMapping(value = "/picture/{id}", method = RequestMethod.GET)
	public void picture(HttpServletRequest request,HttpServletResponse response, @PathVariable Long id) {
		// Image image = imageService.get(id);
		Image image = new Image();
		File imageFile = new File(ServerPathUtils.getImageDir(request) + "/" + image.getNewFilename());
		response.setContentType(image.getContentType());
		response.setContentLength(image.getSize().intValue());
		try {
			InputStream is = new FileInputStream(imageFile);
			IOUtils.copy(is, response.getOutputStream());
		} catch (IOException e) {
			logger.error("Could not show picture " + id, e);
		}
	}

	@RequestMapping(value = "/thumbnail/{id}", method = RequestMethod.GET)
	public void thumbnail(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
		// Image image = imageDao.get(id);
		Image image = new Image();
		File imageFile = new File(ServerPathUtils.getImageDir(request) + "/" + image.getThumbnailFilename());
		response.setContentType(image.getContentType());
		response.setContentLength(image.getThumbnailSize().intValue());
		try {
			InputStream is = new FileInputStream(imageFile);
			IOUtils.copy(is, response.getOutputStream());
		} catch (IOException e) {
			logger.error("Could not show thumbnail " + id, e);
		}
	}

	@RequestMapping(value = "/delete/{uuid}", method = RequestMethod.DELETE)
	@ResponseBody
	public List<Map<String, Object>> delete(HttpServletRequest request, @PathVariable String uuid) {
		Image image = imageService.getByUuid(uuid);
		// 删除文件
		File imageFile = new File(ServerPathUtils.getImageDir(request) + "/" +image.getNewFilename());
		imageFile.delete();
		File thumbnailFile = new File(ServerPathUtils.getImageDir(request) + "/" + image.getThumbnailFilename());
		thumbnailFile.delete();
		
		// 删除数据库
		imageService.deleteByUuid(uuid);
		List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
		Map<String, Object> success = new HashMap<String, Object>();
		success.put("success", true);
		results.add(success);
		return results;
	}
	
	public ShiroUser getCurrentUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}
}
